package com.clss.uvctest;

import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.clss.uvctest.webrtcController.WebRtcSignController;
import com.clss.uvctest.webrtcController.WebRtcSignListener;
import com.clss.webrtclibrary.IVideoRoomListener;
import com.clss.webrtclibrary.KurentoSignallingBean;
import com.clss.webrtclibrary.Lg;
import com.clss.webrtclibrary.LiveVideoRoom;
import com.clss.webrtclibrary.MediaInfoBean;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;
import org.webrtc.SurfaceViewRenderer;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.plugins.RxJavaPlugins;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author liuv
 */

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
//    public static final String BASE_URL = "http://192.168.0.139:8080/skynet/";
    public static final String BASE_URL = "https://hb.video110.cn:8000/skynet/";
//    public static final String BASE_URL = "https://qa-mysql.video110.cn:8000/skynet/";
//    public static final String BASE_URL = "https://qa.video110.cn/skynet/";
//    public static final String BASE_URL = "https://demo.video110.cn:8000/skynet/";
//    public static final String BASE_URL_1 = "https://be.video110.cn:8000/skynet/";
//    public static final String BASE_URL = "https://www.video110.cn:8033/skynet/";
//    public static final String BASE_VIDEO_URL = "wss://www.video110.cn:8000/skynet/ws/";
//    public static final String BASE_VIDEO_URL = "wss://he.video110.cn:8000/skynet/ws/";
//    public static final String BASE_VIDEO_URL = "wss://www.video110.cn:8033/skynet/ws/";
//    public static final String BASE_URL = "http://192.168.0.8:9001/skynet/";
//    public static final String BASE_URL = "http://192.168.0.162:8080/skynet/";
//    public static final String BASE_VIDEO_URL = "ws://192.168.100.50:8080/skynet/ws/";
//    public static final String BASE_VIDEO_URL = "ws://192.168.0.79:8080/skynet/ws/";

    private MediaInfoBean mediaInfoBean;
    private LiveVideoRoom liveVideoRoom;
    private SurfaceViewRenderer localRenderer, remoteRenderer;
    private int mH, mW;
    private Retrofit mRetrofit;
    private boolean isEnable = true;
    private Intent mScreenIntent;
    private static long TIME_OUT = 1000 * 60;
    private TextView mCWtv, mCHtv, mSWtv, mSHtv;

    public static String id = "";

    private WebRtcSignController mWebRtcSignController;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RxJavaPlugins.setErrorHandler(throwable -> {
            Lg.e(TAG, "---RxJava报错了===" + throwable.toString());
        });

        localRenderer = findViewById(R.id.local_view);
        remoteRenderer = findViewById(R.id.remote_view);
        remoteRenderer.setZOrderMediaOverlay(true);
        remoteRenderer.getHolder().setFormat(PixelFormat.TRANSLUCENT);

//        joinVideoRoom();
        ViewGroup.LayoutParams layoutParams = remoteRenderer.getLayoutParams();
        mH = layoutParams.height;
        mW = layoutParams.width;
        initVideo();
//        ImageView imageView = findViewById(R.id.image_test);
//        Glide.with(this).load(R.drawable.bug).into(imageView);
        mCWtv = findViewById(R.id.camera_w_tv);
        mCHtv = findViewById(R.id.camera_h_tv);
        mSWtv = findViewById(R.id.send_w_tv);
        mSHtv = findViewById(R.id.send_h_tv);
    }

    private void initVideo(){
        Lg.i(TAG, "---initVideo===");
//        joinVideoRoom("90726");
        createVideoCase();
//        MediaProjectionManager mMediaProjectionManager = (MediaProjectionManager) getApplication().getSystemService(Context.MEDIA_PROJECTION_SERVICE);
//        startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(), 666);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 666){
            mScreenIntent = data;
//            createVideoCase();
        }
    }

    private void joinVideoRoom(String taskName){
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(TIME_OUT, TimeUnit.MILLISECONDS)
                .readTimeout(TIME_OUT, TimeUnit.MILLISECONDS)
                .writeTimeout(TIME_OUT, TimeUnit.MILLISECONDS).build();

        mRetrofit = new Retrofit.Builder()
                .baseUrl("https://hbyj.video110.cn:8000/skynet/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
        Map<String, String> map = new HashMap<>();
        map.put("taskName", taskName);

        mRetrofit.create(ApiList.class).joinRoom(SpHelper.getInstance().getToken(), map).enqueue(new Callback<BaseJson>() {
            @Override
            public void onResponse(Call<BaseJson> call, Response<BaseJson> response) {
                BaseJson baseJson = response.body();
                Lg.i(TAG, "---onResponse===" + baseJson.toString());
                if (baseJson == null){
                    return;
                }
                if (baseJson.getCode() != 0){
                    Toast.makeText(MainActivity.this, baseJson.getError(), Toast.LENGTH_LONG).show();
                    return;
                }
                mediaInfoBean = new Gson().fromJson(baseJson.getObj(), MediaInfoBean.class);
                Lg.i(TAG, "---mediaInfoBean===" + mediaInfoBean.toString());
//                        mediaInfoBean.setPin("VxMq");
//                        mediaInfoBean.setId("129fcdc0-d6a9-11e8-a1b4-43e9138345af");
//                        mediaInfoBean.setTurnAddress("turn:211.90.39.21:7811");
//                        mediaInfoBean.setTurnUser("video110");
//                        mediaInfoBean.setTurnPassword("8b9f9d90-d500-11e8-a1d4-83760b57ada8");
                initSignControll();
            }

            @Override
            public void onFailure(Call<BaseJson> call, Throwable t) {
                Lg.i(TAG, "---onFailure===" + t.getMessage());

            }
        });

    }

    private void createVideoCase() {
        Lg.i(TAG, "---createVideoCase===");

        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(TIME_OUT, TimeUnit.MILLISECONDS)
                .readTimeout(TIME_OUT, TimeUnit.MILLISECONDS)
                .writeTimeout(TIME_OUT, TimeUnit.MILLISECONDS).build();

        mRetrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

        Map<String, String> body = new HashMap<>();
        body.put("address", "河北省石家庄市桥西区西二环南路辅路188号靠近石家庄市水产管理处");
        body.put("fromMarkId", "");
        body.put("latitude", "38.021019");
        body.put("longitude", "114.433305");
        body.put("show", "true");
        body.put("description", "实时报警");
        body.put("type", "100");
        body.put("province", "河北省");
        body.put("city", "石家庄市");
        body.put("district", "桥西区");
        body.put("caseProvince", "河北省");
        body.put("caseCity", "石家庄市");
        body.put("caseDistrict", "桥西区");
        body.put("fromMark", "person");
//        body.put("taskId", "9a294bd0-5e37-11e8-99ff-8b9f6919a176");
//        body.put("dispatchId", "9a33ac10-5e37-11e8-99ff-8b9f6919a176");

//        body.put("isNew", "0");
//        body.put("longitude", "114.433305");
//        body.put("latitude", "38.023506");
//        body.put("address", "河北省石家庄市桥西区槐安西路260号靠近乐橙商务广场2号公寓");

        mRetrofit.create(ApiList.class).addVideoCase(SpHelper.getInstance().getToken(), body)
//        mRetrofit.create(ApiList.class).safetyAddVideoCase(SpHelper.getInstance().getToken())
//        mRetrofit.create(ApiList.class).joinVideoRoom(SpHelper.getInstance().getToken(), body)
                .enqueue(new Callback<BaseJson>() {
                    public void onResponse(Call<BaseJson> call, Response<BaseJson> response) {

                        BaseJson baseJson = response.body();
                        Lg.i(TAG, "---onResponse===" + baseJson.toString());
                        if (baseJson == null){
                            return;
                        }
                        if (baseJson.getCode() != 0){
                            Toast.makeText(MainActivity.this, baseJson.getError(), Toast.LENGTH_LONG).show();
                            return;
                        }
                        mediaInfoBean = new Gson().fromJson(baseJson.getObj(), MediaInfoBean.class);
                        Lg.i(TAG, "---mediaInfoBean===" + mediaInfoBean.toString());
//                        mediaInfoBean.setPin("VxMq");
//                        mediaInfoBean.setId("129fcdc0-d6a9-11e8-a1b4-43e9138345af");
//                        mediaInfoBean.setTurnAddress("turn:211.90.39.21:7811");
//                        mediaInfoBean.setTurnUser("video110");
//                        mediaInfoBean.setTurnPassword("8b9f9d90-d500-11e8-a1d4-83760b57ada8");
                        initSignControll();
                    }

                    @Override
                    public void onFailure(Call<BaseJson> call, Throwable t) {
                        Lg.i(TAG, "---onFailure===" + t.getMessage());
                    }
                });
    }

    private void initSignControll() {
        Lg.i(TAG, "---initSignControll===");

        mWebRtcSignController = new WebRtcSignController(new WebRtcSignListener() {
            @Override
            public void signLineIsOpened() {
                initVideoRoom();
            }

            @Override
            public void signLineIsClosed() {

            }

            @Override
            public void hasRemoteSignInfo(@NotNull KurentoSignallingBean remoteSign) {
                if (liveVideoRoom != null) {
                    liveVideoRoom.receivedNewSign(remoteSign);
                }

            }
        }, mediaInfoBean);
        mWebRtcSignController.signLineStartWork();
    }


    private void joinVideoRoom(){
        MediaInfoBean.SignalingBean signalingBean = new MediaInfoBean.SignalingBean();
//        signalingBean.setStompHost("ws://192.168.123.82:8080/skynet/ws/websocket");
        signalingBean.setStompHost("wss://test.video110.cn:8002/skynet/ws/websocket");
        signalingBean.setStompDestination("SIGNALING_handler_16801");
//        signalingBean.setStompDestination("SIGNALING_handler_lichao-mac");
        mediaInfoBean = new MediaInfoBean();
        mediaInfoBean.setPin("DMjD");
        mediaInfoBean.setId("86cafad0-3a68-11e9-9d29-758ff554e8ba");
//        mediaInfoBean.setTurnAddress("turn:211.90.39.21:7811");
        mediaInfoBean.setTurnAddress("turn:211.90.39.22:3478");
        mediaInfoBean.setTurnUser("video110");
        mediaInfoBean.setTurnPassword("8b9f9d90-d500-11e8-a1d4-83760b57ada8");
        mediaInfoBean.setSignalingBean(signalingBean);
        mWebRtcSignController = new WebRtcSignController(new WebRtcSignListener() {
            @Override
            public void signLineIsOpened() {
                initVideoRoom();
            }

            @Override
            public void signLineIsClosed() {

            }

            @Override
            public void hasRemoteSignInfo(@NotNull KurentoSignallingBean remoteSign) {
                if (liveVideoRoom != null) {
                    liveVideoRoom.receivedNewSign(remoteSign);
                }

            }
        }, mediaInfoBean);
        mWebRtcSignController.signLineStartWork();

    }

    private void initVideoRoom(){
//        Lg.i(TAG, "---initVideoRoom===" + mediaInfoBean.toString());
        Lg.i(TAG, "---initVideoRoom===" + getMainLooper().getThread().getName());
        Lg.i(TAG, "---initVideoRoom===" + Thread.currentThread().getName());
        liveVideoRoom = new LiveVideoRoom(mediaInfoBean, localRenderer, remoteRenderer,
                0, new IVideoRoomListener() {
            @Override
            public void videoRoomDisconnect() {

            }

            @Override
            public void videoError(String error) {

            }

            @Override
            public void playIsOver() {

            }

            @Override
            public void videoOnStart() {

            }

            @Override
            public void remoteVideoIsEnable(String s) {

            }

            @Override
            public void newArrivedRoom(KurentoSignallingBean localSign) {

            }

            @Override
            public void leaveRoom() {

            }

            @Override
            public void sendLocalSign(KurentoSignallingBean localSign) {
                mWebRtcSignController.hasLocalSignMessagge(localSign);
            }

            @Override
            public Context getContext() {
                return MainActivity.this;
            }

            @Override
            public void setVideoDuration(long time, String player, boolean isSeekable) {

            }

            @Override
            public void setVideoPosition(long position) {

            }

            @Override
            public void videoConnectionState(String state) {
                Lg.i(TAG, "---videoConnectionState===" + state);
                if(state.contains(",")){
                    showVideoStatusInfo(state);
                }
            }

        });
//        }, mScreenIntent);

    }

    void showVideoStatusInfo(String state){
        runOnUiThread(() -> {
            String cameraWidth = state.split(",")[0];
            String cameraHeight = state.split(",")[1];
            String sendWidth = state.split(",")[2];
            String sendHeight = state.split(",")[3];
            mCWtv.setText("原始宽度：" + cameraWidth);
            mCHtv.setText("原始高度：" + cameraHeight);
            mSWtv.setText("发出宽度：" + sendWidth);
            mSHtv.setText("发出高度：" + sendHeight);
        });
    }

    @Override
    public void finish() {
        stopVideo();
        mWebRtcSignController.disconnectionSignLine();

        super.finish();
    }

    private void stopVideo(){
        if (liveVideoRoom != null){
            liveVideoRoom.stopVideo();
        }
        mRetrofit.create(ApiList.class).stopVideoCall(SpHelper.getInstance().getToken(), mediaInfoBean.getCaseId())
                .enqueue(new Callback<BaseJson>() {
                    @Override
                    public void onResponse(Call<BaseJson> call, Response<BaseJson> response) {

                    }

                    @Override
                    public void onFailure(Call<BaseJson> call, Throwable t) {

                    }
                });
    }
}
